<?php

namespace app\common\business;
use app\common\model\mysql\SysDept as SysDeptModel;

class SysDept
{
    public $deptObj = null;
    public function __construct()
    {
        $this->deptObj = new SysDeptModel();
    }

    //查询部门列表
    public function getNormalDept($where,$field = "*"){
        $deptData = $this->deptObj->getNormalDept($where,$field);
        if(!$deptData){
            return [];
        }
        $deptData = $deptData->toArray();
        return $deptData;
    }

    //部门无限极分类
    public function deptTree($where = []){
        $deptData = $this->deptObj->getDeptTree(0,$where);
        if(!$deptData){
            return [];
        }
        return $deptData;
    }

    //查询部门单条数据
    public function getFindNormalDept($where,$field = "*"){
        $deptData = $this->deptObj->getFindNormalDept($where,$field);
        if(!$deptData){
            return [];
        }
        $deptData = $deptData->toArray();
        return $deptData;
    }

    //添加部门
    public function addDept($data){
        //根据$name,$parentId 去数据库查询是否存在这条记录
        $deptResult = $this->getDeptByName($data['dept_name'],$data['parent_id']);
        if($deptResult){
            throw new \think\Exception("该部门名称已经存在请重新设置");
        }
        try {
            $this->deptObj->save($data);
        }catch (\Exception $e){
            throw new \think\Exception($e->getMessage());
        }
        return $this->deptObj->id;
    }

    /**
     * 根据主键id更新数据表中的数据
     * @param $id
     * @param $data
     * @return bool
     */
    public function updateById($id,$data){
        $id = intval($id);
        if(empty($id) || empty($data) || !is_array($data)){
            return false;
        }
        //根据$name,$parentId 去数据库查询是否存在这条记录
        $deptResult = $this->getDeptByName($data['dept_name'],$data['parent_id'],$id);
        if($deptResult){
            throw new \think\Exception("该部门名称已经存在请重新设置");
        }
        $where = [
            "dept_id"=>$id,
        ];
        return $this->deptObj->where($where)->find()->save($data);
    }

    public function getDeptByName($name,$parentId,$dept_id = ''){
        $user = $this->deptObj->getDeptByDeptname($name,$parentId,$dept_id);
        if(!$user){
            return [];
        }
        return $user->toArray();
    }

    //获取部门下parent_id数组集合
    public function deptParentId(){
        $deptData = $this->deptObj->deptParentIdData();
        if(!$deptData){
            return [];
        }
        return $deptData;
    }

    //根据parent_ids数组获取部门ids数组
    public function deptIds($parentIds){
        $deptData = $this->deptObj->deptIdsData($parentIds);
        if(!$deptData){
            return [];
        }
        return $deptData;
    }
}
